package copyengine.dataLayer.query.local
{
	import copyengine.dataLayer.query.database.CEDatabaseQueryManger;
	import copyengine.utils.tick.GlobalTick;

	import flash.utils.getQualifiedClassName;

	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class CELocalQueryBasic extends Mediator
	{
		protected var param:Object;

		private var result:Object

		private var requestQueryLength:int;

		private var currentQueryCount:int;

		public function CELocalQueryBasic(_name:String, _param:Object = null)
		{
			param = _param;
			super(_name, null);
		}

		override final public function onRegister():void
		{
			result = new Object();
			requestQueryLength = getDatabaseQueryNameList().length;
			var queryNameArray:Array = getDatabaseQueryNameList();
			for (var i:int = 0; i < queryNameArray.length; i++)
			{
				CEDatabaseQueryManger.instance.excuteDatabaseQuery(queryNameArray[i][0], queryNameArray[i][1]);
			}
		}

		override final public function onRemove():void
		{
			result = null;
			param = null;
		}

		override final public function listNotificationInterests():Array
		{
			var queryArray:Array = getDatabaseQueryNameList();
			var listArray:Array = [];
			for (var i:int = 0; i < queryArray.length; i++)
			{
				listArray.push(getQualifiedClassName(queryArray[i][0]));
			}
			return listArray;
		}

		override final public function handleNotification(notification:INotification):void
		{
			var key:String = notification.getName();
			result[key] = notification.getBody();
			currentQueryCount++;
			if (currentQueryCount >= requestQueryLength)
			{
				GlobalTick.instance.callLaterAfterTickCount(finishLocalQuery);
			}
		}

		private function finishLocalQuery():void
		{
			var dto:ICELocalResultDTO = setResultDTO();
			facade.sendNotification(getQualifiedClassName(this), dto);
			facade.removeMediator(getMediatorName());
		}

		protected final function getResultByClass(_class:Class):*
		{
			var className:String = getQualifiedClassName(_class);
			return result[className];
		}

		protected function getDatabaseQueryNameList():Array
		{
			throw new Error("child class should override this function");
		}

		protected function setResultDTO():ICELocalResultDTO
		{
			throw new Error("child class should override this function");
		}

	}
}